/*
 * @Author: yangni 920556271@qq.com
 * @Date: 2023-12-07 09:26:03
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2023-12-25 17:20:33
 * @FilePath: /yt-devops/lib/pages/devices/device_tab/basic_info/sub_debvice_tree/sub_debvice_tree_controller.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'package:get/get.dart';
import 'package:yt_devops/components/yt_expandable_tree/model/m_stack.dart';
import 'package:yt_devops/components/yt_expandable_tree/model/tree_mode.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/utils/toast_utils.dart';

class SubDebviceTreeController extends GetxController {
  DeviceServices service = DeviceServices();
  int? siteId;

  List<TreeNode> treeData = [];

  List selectedDeviceIds = [];

  List<TreeNode> selectedTreeNode = [];

  List initSelectedDeviceIds = [];

  List data = [];

  @override
  void onInit() {
    super.onInit();
    var args = Get.arguments;
    if (args != null) {
      siteId = args['siteId'];
      if (args['selectDeviceIds'] is List) {
        selectedDeviceIds =
            args['selectDeviceIds'].map((e) => e['id']).toList();
      }

      if (siteId != null) {
        getAssociateDevice();
      } else {
        TotastUtils.tip(Get.context!, title: '无法查询该站点下的设备');
      }
    }
  }

  @override
  void onReady() {}

  @override
  void onClose() {}

  getAssociateDevice() => Configs.httpClient.requestWithLoading(() async {
        data = await service.deviceTree({'siteId': siteId, 'isConfine': 0});
        treeData = getTreeData(data, null, 0);
        update();
      });

  List<TreeNode> getTreeData(List data, String? parentValue, int level) =>
      treeData = TreeNode.listFrom(
          source: data,
          checkable: (index, item) => level == 0 ? false : true,
          value: (index, item) {
            var value = parentValue == null ? '$index' : '$parentValue-$index';
            if (selectedDeviceIds.contains(item['id'])) {
              initSelectedDeviceIds.add(value);
            }
            return value;
          },
          title: (index, item) => item['deviceName'],
          subNodes: (index, item) => getTreeData(
              item['children'],
              parentValue == null ? '$index' : '$parentValue-$index',
              level + 1));

  checkHandle(List<TreeNode> nodes) {
    selectedTreeNode = nodes;
  }

  save() {
    List<Map> selectedMapList = [];
    for (var i = 0; i < selectedTreeNode.length; i++) {
      MStack m = MStack();
      if (selectedTreeNode[i].subNodes?.isNotEmpty == true) {
        m.push(selectedTreeNode[i]);
        while (m.top > 0) {
          var item = m.pop();
          for (var child in item.subNodes ?? []) {
            if (child.subNodes?.isNotEmpty == true) {
              m.push(child);
            } else {
              var valueList =
                  child.value.split('-').map((e) => int.parse(e)).toList();
              if (valueList.length == 3) {
                var map = data[valueList[0]]['children'][valueList[1]]
                    ['children'][valueList[2]];
                selectedMapList.add(map);
              }
            }
          }
        }
      } else {
        var valueList = selectedTreeNode[i]
            .value
            .split('-')
            .map((e) => int.parse(e))
            .toList();
        if (valueList.length == 3) {
          var map = data[valueList[0]]['children'][valueList[1]]['children']
              [valueList[2]];
          selectedMapList.add({
            'name': map['deviceName'],
            'id': map['id'],
          });
        }
      }
    }
    Get.back(result: selectedMapList);
  }
}
